package com.wocai.jrt.admin.user.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.vteba.service.generic.impl.MyBatisServiceImpl;
import com.vteba.tx.jdbc.mybatis.spi.BaseDao;
import com.vteba.utils.json.FastJsonUtils;
import com.wocai.jrt.admin.common.bean.Icon;
import com.wocai.jrt.admin.common.bean.Node;
import com.wocai.jrt.admin.common.bean.State;
import com.wocai.jrt.admin.user.dao.ResourcesDao;
import com.wocai.jrt.admin.user.model.AuthResource;
import com.wocai.jrt.admin.user.model.Authorities;
import com.wocai.jrt.admin.user.model.Resources;
import com.wocai.jrt.admin.user.model.ResourcesBean;
import com.wocai.jrt.admin.user.service.spi.AuthResourceService;
import com.wocai.jrt.admin.user.service.spi.ResourcesService;
import com.wocai.jrt.orgadmin.utils.UserUtils;

/**
 * 资源表相关的service业务实现。
 * @author yinlei
 * @date 2015-7-6 11:40:40
 */
@Named
public class ResourcesServiceImpl extends MyBatisServiceImpl<Resources, ResourcesBean, String> implements ResourcesService {
	private static final Logger LOGGER = LoggerFactory.getLogger(ResourcesServiceImpl.class);
	
	private ResourcesDao resourcesDao;
	
	@Inject
	private AuthResourceService authResourceServiceImpl;
	
	@Override
	@Inject
	public void setBaseDao(BaseDao<Resources, ResourcesBean, String> resourcesDao) {
		this.baseDao = resourcesDao;
		this.resourcesDao = (ResourcesDao) resourcesDao;
	}

	@Override
	public List<Resources> queryResourceList(String authId) {
		return resourcesDao.queryResourceList(authId);
	}

	@Override
	public Node getResourceTree(Resources model) {
		// 根节点
		Node root = new Node();
		root.setText("系统资源");
		root.setId("-1");
		root.setIcon(Icon.BRIEF_WARN);
		try {
			// 以后放到缓存
			Resources resParam = new Resources();
			resParam.setOrgId(UserUtils.getOrgId());
			List<Resources> list = queryListByOrgId(resParam);
			Map<String, List<Node>> maps = new HashMap<String, List<Node>>();
			Set<String> resourceIdSet = new HashSet<String>();
			
			// 前端就是用resourceId封装的authId
			String authId = model.getResourceId();
			
			// authId不为空，且不等于null，才查询
			if (authId != null && !authId.equals("null")) {
				AuthResource params = new AuthResource();
				params.setAuthId(authId);
				List<AuthResource> authResList = authResourceServiceImpl.queryList(params);
				// 将资源id放入set，供下面判断
				for (AuthResource ar : authResList) {
					resourceIdSet.add(ar.getResourceId());
				}
				State state = new State();
				state.setOpened(true);
				root.setState(state);
			}
			
			// 将资源进行分组
			for (Resources bean : list) {
				String url = bean.getResourceUrl();
				String[] urls = StringUtils.split(url, "/");
				String prefix = StringUtils.capitalize(urls[0]);
				List<Node> nodes = maps.get(prefix);
				if (nodes == null) {
					nodes = new ArrayList<Node>();
					maps.put(prefix, nodes);
				}
				
				Node node = new Node();
				String resourceId = bean.getResourceId();
				if (resourceIdSet.contains(resourceId)) {
					State state = new State();
					state.setSelected(true);
					state.setLoaded(true); // 如果不设，将会出现+号，阿西吧
					node.setState(state);
				}
				node.setId(resourceId);
				node.setText(bean.getResourceName());
				node.setIcon(Icon.FILE_DANGER);
				nodes.add(node);
			}
			
			// 构造分组节点，当资源很多时，便于选择
			List<Node> nodeList = new ArrayList<Node>();
			for (Entry<String, List<Node>> entry : maps.entrySet()) {
				Node node = new Node();
				node.setId(entry.getKey());
				node.setText(entry.getKey());
				node.setChildren(entry.getValue());
				
				nodeList.add(node);
			}
			root.setChildren(nodeList);
		} catch (Exception e) {
			LOGGER.error("build resources tree error, msg=[{}].", e.getMessage());
		}
		if (LOGGER.isInfoEnabled()) {
			LOGGER.info("tree json =[{}].", FastJsonUtils.toJson(root));
		}
		return root;
	}

	@Override
	public List<Resources> queryListByAuth(Authorities params) {
		return resourcesDao.queryListByAuth(params);
	}

	@Override
	public List<Resources> queryListByOrgId(Resources params) {
		return resourcesDao.queryListByOrgId(params);
	}
}
